package com.leyou.auth.scheduled;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class AppTokenScheduled {

    /**
     * token刷新间隔
     */
    private static final long TOKEN_REFRESH_INTERVAL = 86400000L;
    /**
     * token获取失败后重试的间隔
     */
    private static final long TOKEN_RETRY_INTERVAL = 10000L;
    /**
     * 提供一个存储token的属性
     */
    private String token;
    /**
     * 获取token相关配置信息
     */
    @Autowired
    private JwtProperties jwtProp;
    /**
     * 调用获取token的AuthService
     */
    @Autowired
    private AuthService authService;

    @Scheduled(fixedDelay = TOKEN_REFRESH_INTERVAL)
    public void autoAppAuth(){
        //调用feign接口获取token
        String token = null;
        while (true){
            try {
                //获取token
                token = authService.authorize(jwtProp.getApp().getId(), jwtProp.getApp().getServiceName());
                //把token赋值给
                this.token = token;
                log.info("【{}服务获取token成功！】", jwtProp.getApp().getServiceName());
                //如果获取成功，要结束死循环
                break;
            }catch (Exception e){
                log.error("【{}服务获取token失败！】稍微将重试", jwtProp.getApp().getServiceName());
            }
            //休息十秒钟
            try {
                Thread.sleep(TOKEN_RETRY_INTERVAL);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


    }

    /**
     * 提供一个获取token的方法
     */
    public String getToken() {
        return token;
    }

}
